module.exports = app => {
  const express = require('express')
  const router = express.Router()
  const AdminUser = require('../../models/AdminUser')
  const bcryptjs = require('bcryptjs')
  const jwt = require('jsonwebtoken')
  const assert = require('http-assert')
  const authMiddleWare = require('../../middleWare/auth')
  // const throwError = require('../../middleWare/throwErr')

  // 登陆成功显示用户名
  router.get('/', authMiddleWare(), async (req, res) => {
    console.log(req.user)
    res.send({ username: req.user.username })
  })
  // 登录接口
  router.post('/', async (req, res) => {
    // 客户端传来的数据解构
    const { username, password } = req.body
    // 1.根据用户名找用户  --  数据库查出的数据
    const user = await AdminUser.findOne({ username }).select('+password')
    // 抛出异常
    assert(user, 422, '用户不存在')
    // 2.用户存在,校验密码
    const isValid = bcryptjs.compareSync(password, user.password)
    assert(isValid, 422, '密码错误')
    // 3. 校验通过，返回token
    const token = jwt.sign({
      id: user._id,
      username: user.username
    }, app.get('secret'), { algorithm: 'HS256' })
    res.send({
      token
    })
  })

  app.use('/admin/api/login', router)
}